#!/bin/bash
# Linux/macOS build script for AI-Powered SSH Terminal
# Builds executable with optimizations for Unix deployment

echo "========================================"
echo " AI-Powered SSH Terminal - Unix Build"
echo "========================================"

# Check if in conda environment
if [ -z "$CONDA_DEFAULT_ENV" ]; then
    echo "⚠️  WARNING: Not in a conda environment"
    echo "Recommended: conda activate ai-terminal"
    echo ""
fi

# Check if Python and PyInstaller are available
if ! command -v python &> /dev/null; then
    echo "❌ ERROR: Python not found in PATH"
    exit 1
fi

if ! python -c "import PyInstaller" &> /dev/null; then
    echo "❌ ERROR: PyInstaller not installed"
    echo "Install with: pip install -r pyinstaller_requirements.txt"
    exit 1
fi

echo "🔨 Building AI-Powered SSH Terminal for $(uname)..."
echo ""

# Set default build options
BUILD_TYPE="dir"
INCLUDE_MODEL=false
CREATE_PACKAGE=true

# Parse command line arguments
while [[ $# -gt 0 ]]; do
    case $1 in
        --onefile)
            BUILD_TYPE="onefile"
            shift
            ;;
        --include-model)
            INCLUDE_MODEL=true
            shift
            ;;
        --no-package)
            CREATE_PACKAGE=false
            shift
            ;;
        *)
            echo "Unknown option: $1"
            echo "Usage: $0 [--onefile] [--include-model] [--no-package]"
            exit 1
            ;;
    esac
done

# Clean previous builds
echo "🧹 Cleaning previous builds..."
rm -rf build dist

# Build executable
echo "🚀 Starting build process..."
python build_executable.py --build-type "$BUILD_TYPE"

if [ $? -ne 0 ]; then
    echo ""
    echo "❌ Build failed"
    exit 1
fi

# Create package if requested
if [ "$CREATE_PACKAGE" = true ]; then
    echo ""
    echo "📦 Creating distribution package..."
    python build_executable.py --package
fi

echo ""
echo "========================================"
echo " ✅ Build Complete!"
echo "========================================"
echo ""
echo "📂 Executable location: dist/AI-Terminal/"
echo ""
echo "🧪 To test the executable:"
echo "   cd dist/AI-Terminal"
echo "   ./AI-Terminal"
echo ""

if [ "$CREATE_PACKAGE" = true ]; then
    echo "📦 Distribution package: AI-Terminal-Package/"
    echo ""
fi

# Ask if user wants to test immediately
read -p "🤔 Test the executable now? (y/n): " test
if [[ $test =~ ^[Yy]$ ]]; then
    echo ""
    echo "🚀 Starting AI-Terminal..."
    cd dist/AI-Terminal
    ./AI-Terminal &
    cd ../..
    echo "✓ AI-Terminal started in background"
fi